<template>
    <div>
        <h-section title="生成需求台账多维表格" collapse>
            <flexbox justify="flex-end">
                <a-button type="primary" @click="handleCreate">新增</a-button>
            </flexbox>
            <a-table rowKey="id" size="small" :loading="loadingObj" :columns="tableColumns" :data-source="list" :pagination="false">
                <template #fsUrl="{ record }">
                    <a @click="handleJumpTo(record.fsUrl)" v-if="record.fsUrl">查看</a>
                </template>
                <template #action="{ record }">
                    <a @click="handleEdit(record.id)">修改模板</a>
                    <a-divider type="vertical" />
                    <a @click="handleSync(record.id)" v-if="record.syncStatus">更新多维表格</a>
                    <a @click="handleSync(record.id)" v-else>同步多维表格</a>
                    <a-divider type="vertical" />
                    <a @click="handleDelete(record)">删除</a>
                </template>
            </a-table>
        </h-section>
        <create-modal v-model:visible="visible" :detail="detailData" :info="info" v-if="visible" @success="handleSuccess" />
    </div>
</template>

<script lang="ts">
import api from '@/api';
import { message } from 'ant-design-vue/es';
import { useMessage } from '@/hooks/common/useMessage';
import CreateModal from './components/createModal.vue';
import { defineComponent, ref, unref, reactive, toRefs, computed } from 'vue';
export default defineComponent({
    components: {
        CreateModal
    },
    props: {
        list: {
            type: Array,
            default: []
        },
        info: {
            type: Object,
            default: () => ({})
        }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const state = reactive<any>({
            visible: false,
            loadingTip: '',
            loading: false,
            timer: null,
            detailData: {}
        });
        const loadingObj = computed(() => {
            const obj = {
                tip: state.loadingTip,
                loading: state.loading
            };
            return state.loading ? obj : false;
        });
        const tableColumns = [
            {
                title: '模板名称',
                dataIndex: 'tempName',
                ellipsis: true
            },
            {
                title: '需求台账多维表格唯一标识（app_token)',
                dataIndex: 'fsToken',
                width: 350
            },
            {
                title: '飞书链接',
                dataIndex: 'fsUrl',
                slots: { customRender: 'fsUrl' }
            },
            {
                title: '操作',
                dataIndex: '',
                key: 'action',
                slots: { customRender: 'action' },
                align: 'center',
                width: 300
            }
        ];

        const handleJumpTo = (url) => {
            if (props.info.accountStatus === '已失效') {
                message.error('用户访问凭证失效，请重新获取');
                return;
            }
            window.open(url);
        };
        const handleCreate = () => {
            if (props.info.accountStatus === '未登录') {
                message.error('请先登录飞书');
                return;
            }
            state.visible = true;
            state.detailData = {};
        };
        const handleEdit = async (id) => {
            const query = {
                id
            };
            const { success, moule } = await api.feishuModel.findTempInfoById(query);
            if (success) {
                state.visible = true;
                state.detailData = {
                    ...moule
                };
            }
        };
        const handleUpdate = async (id) => {
            const query = {
                id
            };
            const { success } = await api.feishuModel.syncRecordsToBitables(query);
            if (success) {
                message.success('同步成功');
            } else {
                message.error('同步失败');
            }
        };
        const handleSync = async (id) => {
            if (props.info.accountStatus === '已失效') {
                message.error('用户访问凭证失效，请重新获取');
                return;
            }
            const query = {
                id
            };
            state.loading = true;
            state.loadingTip = '请耐心等待，请勿刷新页面';
            api.feishuModel.syncRecordsToBitables(query).then(({ success, errorMsg }) => {
                if (success) {
                    getItemStatus(id);
                    state.timer = setInterval(() => {
                        getItemStatus(id);
                    }, 10 * 1000);
                } else {
                    state.loading = false;
                    state.loadingTip = '';
                    message.error(errorMsg);
                }
            });
        };
        const handleDelete = ({ id, tempName, fsToken }) => {
            if (fsToken) {
                if (props.info.accountStatus === '已失效') {
                    message.error('用户访问凭证失效，请重新获取');
                    return;
                }
            }
            const { createConfirm } = useMessage();
            createConfirm({
                title: `确认删除【${tempName}】?`,
                iconType: 'danger',
                onOk: async () => {
                    const query = {
                        id
                    };
                    const { success } = await api.feishuModel.deleteTemp(query);
                    if (success) {
                        message.success('删除成功');
                        emit('success');
                    } else {
                        message.error('删除失败');
                    }
                }
            });
        };
        // 获取状态
        const getItemStatus = async (id) => {
            const query = {
                id
            };
            const { success, moule, errorMsg } = await api.feishuModel.findTempInfoById(query);
            if (success) {
                if (moule.syncStatus === '0') {
                    state.timer && clearInterval(state.timer);
                    state.loading = false;
                    state.loadingTip = '';
                    emit('success');
                }
                if (moule.syncStatus === '2') {
                    state.timer && clearInterval(state.timer);
                    state.loading = false;
                    state.loadingTip = '';
                    message.error(moule.jiraSyncMessage);
                }
            } else {
                message.error(errorMsg);
            }
        };
        const handleSuccess = () => {
            emit('success');
        };
        return {
            tableColumns,
            ...toRefs(state),
            loadingObj,
            handleCreate,
            handleEdit,
            handleSync,
            handleUpdate,
            handleDelete,
            handleJumpTo,
            handleSuccess
        };
    }
});
</script>

<style scoped>
</style>